package org.winexpress

import grails.converters.JSON
import org.codehaus.groovy.grails.web.json.JSONObject
import org.codehaus.groovy.grails.web.json.JSONArray


class ShoppingCartController {
    // shared methods
    def sendResponse(statusCode) {
        if (statusCode == 404) {
            JSONObject o = new JSONObject()
            o.put(statusCode, true)
            render o as JSON
        }
        
        response.status = statusCode
        render response
        
        // 200-OK (e.g. GET success)
        // 201-Created (e.g. POST success)
        // 403-Forbidden (e.g. LOGIN failure)
        // 400-Bad Request (e.g. PUT,POST,DELETE failure)
        // 404-Not Found (e.g. GET failure)
        // 500-Internal Server Error (other...)
    }
    
    def retrieveCountryByID(countryId) {
        
        // consume winexpress server web service
        def txt = new URL("http://localhost:8080/WineXpress/country/" + countryId).text
        
        println "get country text " + txt
        
        if (txt.getAt(0) == '{') {
            JSONObject o = new JSONObject(txt)
            if (o.has("404")) {
                if (o.get("404") == true) {
                    println 'No such country.<br/><br/>'
                    return null
                }
            }
            else {
                Country c = new Country()
                c.id = o.get("id")
                c.countryName = o.get("countryName")
                return c
            }
        }
        else {
            println 'No such country.<br/><br/>'
            return null
        }
    }
    
    def retrieveCustomerByID(customerId) {
        
        // consume winexpress server web service
        def txt = new URL("http://localhost:8080/WineXpress/customer/" + customerId).text
        
        println "get cust text " + txt
        
        if (txt.getAt(0) == '{') {
            JSONObject o = new JSONObject(txt)
            if (o.has("404")) {
                if (o.get("404") == true) {
                    println 'No such customer.<br/><br/>'
                    return null
                }
            }
            else {
                Customer c = new Customer()
                c.id = o.get("id")
                c.username = o.get("username")
                c.password = o.get("password")           
//                if (o.get("lastLogin") == null) {
//                    c.
//                }
//                else {
                IntRange indexRangeYear = new IntRange(0,3)
                IntRange indexRangeMonth = new IntRange(5,6)
                IntRange indexRangeDay = new IntRange(8,9)
                def llYear = o.get("lastLogin").getAt(indexRangeYear)
                def llMonth = o.get("lastLogin").getAt(indexRangeMonth)
                def llDay = o.get("lastLogin").getAt(indexRangeDay)
                Date convertedLL = new Date()
                convertedLL.setDate(llDay.toInteger())
                convertedLL.setMonth(llMonth.toInteger()-1)
                convertedLL.setYear(llYear.toInteger())
                convertedLL.setHours(0)
                convertedLL.setMinutes(0)
                convertedLL.setSeconds(0)
                    c.lastLogin = convertedLL
//                }
                c.activationStatus = o.get("activationStatus")
                c.lastName = o.get("lastName")
                c.firstName = o.get("firstName")
//                c.birthdate = o.get("birthdate")
c.birthdate = null
                c.email = o.get("email")
                c.blkHouseNo = o.get("blkHouseNo")
                c.streetName = o.get("streetName")
                c.unitNo = o.get("unitNo")
                c.postalCode = o.get("postalCode")
                c.telNo = o.get("telNo")
                c.country = retrieveCountryByID(o.get("countryId"))
                
                return c
            }
        }
        else {
            println 'No such customer.<br/><br/>'
            return null
        }
    }
    
    

    // REST operations
    // GET
    def show = {
        println 'ShoppingCartController >> Show >> START'
        
        ShoppingCartManagement scman = new ShoppingCartManagement()
        
        if (params.cartId && ShoppingCart.exists(params.cartId)) {    
            def sc = scman.getShoppingCartByID(params.cartId)
            render sc as JSON
            sendResponse(200)
            
            println 'Show shopping cart by ID >> ' + sc.id + " " + sc
        }
        else {
            def allSC = scman.listShoppingCarts()
            if (allSC.length() > 0) {
                render allSC as JSON
                sendResponse(200)
            }
            else {
                sendResponse(404)
            }  
            
            println 'Listing all shopping cart >> ' + allSC
        }
        
//        println 'ShoppingCartController >> Show >> END'
    }
    
    def showByCustomerId = {
        println 'ShoppingCartController >> showByCustomerId >> START'
        
        ShoppingCartManagement scman = new ShoppingCartManagement()
        
        if (params.customerId && Customer.exists(params.customerId)) {    
            def sc = scman.getShoppingCartByCustomerID(params.customerId)
            render sc as JSON
            sendResponse(200)
            
            println 'Show shopping cart by CUST ID >> ' + sc.id + " " + sc
        }
        
        println 'ShoppingCartController >> Show >> END'
    }
    
    
    // PUT
    def update = {
        println 'ShoppingCartController >> Update >> START'
        
        ShoppingCartManagement scman = new ShoppingCartManagement()
           
        JSONObject o = request.JSON
            
        def sc = scman.getShoppingCartByID(o.get("id"))
        if (o.has("costPrice")) { sc.costPrice = o.costPrice }
        if (o.has("sellingPrice")) { sc.sellingPrice = o.sellingPrice }
        if (o.has("stockCount")) { sc.stockCount = o.stockCount }
        
        def result = scman.updateShoppingCart(i)
        if (result == true) {
            println 'ShoppingCartController >> Update >> ' + result
            sendResponse(200)
        }
        else {
            println 'ShoppingCartController >> Update >> ' + result
            sendResponse(400)
        }
        

        println 'ShoppingCartController >> Update >> END'

    }
    
    
    // DELETE
    def delete = {
        println 'ShoppingCartController >> delete >> START'
        
        ShoppingCartManagement scman = new ShoppingCartManagement()
        
        if (params.cartId && ShoppingCart.exists(params.cartId)) {    
            def result = scman.deleteShoppingCart(cartId)
            
            if (result == true) {
                println 'ShoppingCartController >> delete >> ' + result
                sendResponse(200)
            }
            else {
                println 'ShoppingCartController >> delete >> ' + result
                sendResponse(400)
            }
        }
        
        println 'ShoppingCartController >> delete >> END'
    }
    
    
    // POST
    def save = {
        println 'ShoppingCartController >> Save >> START'
        
        JSONObject o = request.JSON
        println o
        
        def cust = null
        if (o.has("customerId")) {
            def customerId = o.get("customerId")

    //        def c = forward(controller:"webService", action:"retrieveCustomerByID", params:[customerId: customerId])
            cust = retrieveCustomerByID(customerId)
            println "retrieved and back in SC SAVE :: " + cust
        }
        
        ShoppingCartManagement scman = new ShoppingCartManagement()
        
        UniqueKeyGenerator key = new UniqueKeyGenerator()
        def k = key.generate()
            
        def result = scman.addShoppingCart(cust, k)
        if (result == false) {
            println 'ShoppingCartController >> Save >> ' + result
            sendResponse(400)
        }
        else {
            println 'ShoppingCartController >> Save >> ' + result
            if (cust == null) {
//                JSONObject oUK = new JSONObject()
//                oUK.put("uniqueKey",k)
//                render oUK as JSON
                sendResponse(201)
            }
            else {
//                JSONObject oID = new JSONObject()
//                oID.put("uniqueKey",result.id)
//                render oID as JSON
                sendResponse(201)
            }
        }
        
        println 'ShoppingCartController >> Save >> END'
    }
    
}
